package com.draven.controller;

import com.draven.common.Result;
import com.draven.util.CaptchaUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码控制器
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * 生成验证码
     */
    @GetMapping("/generate")
    public Result<Map<String, String>> generateCaptcha(HttpSession session) {
        // 生成验证码
        String code = CaptchaUtil.generateRandomCode();
        
        // 将验证码存入session
        session.setAttribute("captchaCode", code);
        
        // 返回验证码
        Map<String, String> result = new HashMap<>();
        result.put("code", code);
        
        return Result.success(result);
    }
    
    /**
     * 校验验证码
     */
    @GetMapping("/verify")
    public Result<Boolean> verifyCaptcha(String code, HttpSession session) {
        // 获取session中的验证码
        String captchaCode = (String) session.getAttribute("captchaCode");
        
        // 校验验证码
        boolean isValid = captchaCode != null && captchaCode.equalsIgnoreCase(code);
        
        // 验证完成后，清除session中的验证码
        if (isValid) {
            session.removeAttribute("captchaCode");
        }
        
        return Result.success(isValid);
    }
} 